<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/9
 * Time: 15:05
 */

namespace common\business\employee;

use common\business\CommonHelper;
use common\business\EhrHelper;
use common\consts\CommonResources;
use common\helpers\StringUtil;
use common\models\kingdee\OrgAdmin;
use common\models\Log;
use Yii;
use common\models\Employee;
use common\models\kingdee\Person;
use common\result\ActionResult;
use yii\db\Exception;
use yii\db\Query;
use yii\helpers\Json;

class EmployeeService
{
    /**
     * @var string
     */
    protected $_department_number;
    public function setDepartmentNumber($department_number){
        $this->_department_number = $department_number;
    }

    /**
     * @param callback|null $writeBackHandler
     * @return ActionResult
     */
    public function sync($writeBackHandler = null){
        $totalResult = new ActionResult();

        $db = Person::getDb();

        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $org = OrgAdmin::findOne([
                'FNUMBER' => $this->_department_number
            ]);

            $orgIdParams = [
                'fid' => $org->FID
            ];
            $cmd = $db->createCommand('SELECT t.fid FROM T_ORG_ADMIN t START WITH t.fid = :fid CONNECT BY t.fparentid = PRIOR fid', $orgIdParams);
//        $cmd->bindParam('fid', $orgId);
            try {
                $orgIdArr = $cmd->queryColumn();
            } catch (Exception $e) {
                return null;
            }
        }

        $query = (new Query())->from('T_BD_PERSON TBP')
            ->leftJoin('T_BD_HRWED TBWED', 'TBWED.FID = TBP.FWEDID')
            ->leftJoin('T_BD_NATIONALITY NAT', 'NAT.FID = TBP.FNATIONALITYID')
            ->leftJoin('T_BD_HRFOLK FK', 'FK.FID = TBP.FFOLKID')
            ->leftJoin('T_BD_REGPERMRESIDENCE REGP', 'REGP.FID = TBP.FREGRESIDENCEID')
            ->leftJoin('T_HR_PERSONCONTACTMETHOD THPCM', 'THPCM.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_PERSONPOSITION THPP', 'THPP.FPERSONID = TBP.FID')
            ->leftJoin('T_ORG_POSITION TOPP', 'TOPP.FID = THPP.FPRIMARYPOSITIONID')
            ->leftJoin('T_HR_EMPLABORRELATION THELR', 'THELR.FPERSONID = TBP.FID')
            ->leftJoin('T_HR_BDEMPLOYEETYPE THBET', 'THBET.FID = THELR.FLABORRELATIONSTATEID')
            ->leftJoin('T_ORG_ADMIN TOA', 'TOA.FID = TOPP.FADMINORGUNITID')
            ->select([
                'name' => 'TBP.FNAME_L2',
                'number' => 'TBP.FNUMBER',
                'gender' => 'TBP.FGENDER',
                'birthday' => 'to_char(FBIRTHDAY , \'yyyy-MM-dd\')',
                'email' => 'TBP.FEMAIL',
                'mobile' => 'TBP.FCELL',
                'id_card_num' => 'TBP.FIDCARDNO',
                'native_place' => 'TBP.FNATIVEPLACE_L2',
                'blood_type' => 'TBP.FBLOODTYPE',
                'wed_status' => 'TBWED.FNAME_L2',
                'nationality' => 'NAT.FNAME_L2',
                'folk' => 'FK.FNAME_L2',
                'hklx' => 'REGP.FNAME_L2',
                'hr_id' => 'TBP.FID',
                'weixin' => 'THPCM.FWEIXIN',
                'position_name' => 'TOPP.FNAME_L2',
                'position_number' => 'TOPP.FNUMBER',
                'labor_relation_state' => 'THBET.FNAME_L2',
                'department_name' => 'TOA.FNAME_L2',
                'department_number' => 'TOA.FNUMBER',
                'department_display_name' => 'TOA.FDISPLAYNAME_L2',
            ]);
        if (!StringUtil::isNullOrWhiteSpace($this->_department_number)){
            $query->andFilterWhere([
                'in' , 'THPP.FPERSONDEP', $orgIdArr
            ]);
        }
        $query->orderBy([
            'TBP.FID' => SORT_ASC,
        ]);

        $totalCount = $query->count('*', $db);

        $offset = 0;
        $pageSize = 100;
        $count = $pageSize;

        while ($count >= $pageSize) {
            $all = $query->offset($offset)->limit($pageSize)->all($db);
            $count = count($all);
            $offset += $pageSize;
            foreach ($all as $person){
                $person['blood_type'] = EhrHelper::getBloodTypeByIntValue($person['blood_type']);

                $newEmployee = new Employee();
                $newEmployee->setAttributes($person);

                $employeeInDb = Employee::findOne([
                    'hr_id' => $newEmployee->hr_id,
                    'id_card_num' => $newEmployee->id_card_num,
                ]);

                $api = new EmployeeApiHandler();
                if (!$employeeInDb){
                    $totalResult->addSubResult($api->createEmployee($newEmployee));
                }
                else {
                    $totalResult->addSubResult($api->updateEmployee($newEmployee, $employeeInDb));
                }
                if ($writeBackHandler){
                    $paramArr = [
                        'totalCount' => $totalCount,
                        'finishCount' => $totalResult->total_count,
                        'message' => $totalResult->message,
                    ];
                    call_user_func_array($writeBackHandler, $paramArr);
                }
            }
        }
        return $totalResult;
    }
}